import React, { Component } from 'react';
import './index.css';
import {getClassify} from '../../../store/actions/classify';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {ClassifyProp} from '../../../types/classify';
import BScroll from 'better-scroll';
import {RouteComponentProps} from 'react-router-dom';

interface Iprops extends RouteComponentProps{
    getClassify:() => void,
    classify:ClassifyProp[]
}

class Classify extends Component<Iprops> {
    scroll: any;
    box: HTMLDivElement | null | undefined;

    componentDidMount(){
        //获取数据
        this.props.getClassify();
        this.scroll = new BScroll('.right',{
            scrollY:true,
            click:true,
            // probeType:2
        })
    }

    componentDidUpdate(){
        this.scroll.refresh();
        //获取到
        //1.获取box下的子节点 2.获取子节点距离顶部的距离 [0,1234,3456]   3.做判断 当前滚动的位置在那个区间
        // this.box.getBoundingClientRect().top
        // this.scroll.on('scroll',(pos:any) => {
        //     console.log(pos)
        // })
    }

    render() {
        let {classify} = this.props;
        return (
            <div className="classify">
                <div className="left">
                    {
                        classify.map((item:ClassifyProp,index:number) => <span key={item.id} onClick={()=>this.scrollTo(index)}>{item.name}</span>)
                    }
                </div>
                <div className="right">
                    <div ref={el => this.box = el}>
                        {
                            classify.map((item) => <div key={item.id}>
                                <h6>{item.name}</h6>
                                <ul>
                                    {item.chidlren.map(v => <li key={v.id} onClick={() => this.goList(v.id)}>{v.text}</li>)}
                                </ul>
                            </div>)
                        }
                    </div>
                </div>
            </div>
        )
    }

    //滚动
    scrollTo = (index:number) => {
        this.scroll.scrollToElement((this.box as HTMLDivElement).children[index],0,0,0);
    }

    //去list
    goList = (id:number) => {
        this.props.history.push(`/list/${id}`)
    }
}


const stateMapToProps = (state:any) => {
    return {
        classify:state.classify
    }
}

const dispatchMapToProps = (dispatch:any) => {
    return bindActionCreators({getClassify},dispatch)
}   

export default connect(stateMapToProps,dispatchMapToProps)(Classify)
